package com.xuelangyun.form.job.command;

import java.util.List;

import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.xuelangyun.form.job.entity.ScheduleJobEntity;
import com.xuelangyun.form.job.service.IScheduleJobService;
import com.xuelangyun.form.job.utils.ScheduleUtils;

/**
 * 启动后初始化扫描当前定时任务列表，确定要初始化的定时任务监听
 *
 * @author weiqing.hk
 */
//@Component
//@Order(2)
public class StartRunner implements CommandLineRunner {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private IScheduleJobService jobService;

    @Override
    public void run(String... args) throws Exception {
        logger.info("start run schedule job ");

        List<ScheduleJobEntity> scheduleJobList = jobService.list();
        for (ScheduleJobEntity scheduleJob : scheduleJobList) {
            CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getJobId());
            //如果不存在，则创建
            if (cronTrigger == null) {
                ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
            } else {
                ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
            }
        }

    }


}
